package com.eeepay.eeepay_v2.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.eeepay.eeepay_v2.R;
import com.eeepay.eeepay_v2.activity.IntoPiecesActivity;
import com.eeepay.eeepay_v2.activity.IntoQueryActivity;
import com.eeepay.eeepay_v2.activity.MerchantQueryActivity;
import com.eeepay.eeepay_v2.activity.MyMerchantActivity;
import com.eeepay.eeepay_v2.activity.NewsCenterActivity;
import com.eeepay.eeepay_v2.activity.QRCodeActivity2;
import com.eeepay.eeepay_v2.activity.ShareActionActivity;
import com.eeepay.eeepay_v2.activity.TradeQueryActivity;
import com.eeepay.eeepay_v2.activity.WeekTradeActivity;
import com.eeepay.eeepay_v2.adapter.SaleAdvAdapter;
import com.eeepay.eeepay_v2.api.GetSuperPushShareStatusAPI;
import com.eeepay.eeepay_v2.app.MyApplication;
import com.eeepay.eeepay_v2.model.UserInfo;
import com.eeepay.eeepay_v2.util.ConfigPorperties;
import com.eeepay.eeepay_v2.util.Constant;
import com.eeepay.eeepay_v2.util.GrpcUtils;
import com.eeepay.eeepay_v2.util.MathUtils;
import com.eeepay.eeepay_v2.view.CustomDisplayView;
import com.eeepay.v2_library.dialog.CustomDialog;
import com.eeepay.v2_library.dialog.DialogUtil;
import com.eeepay.v2_library.log.LogUtils;
import com.eeepay.v2_library.pulltorefresh.PullToRefreshBase;
import com.eeepay.v2_library.pulltorefresh.PullToRefreshScrollView;
import com.eeepay.v2_library.util.ScreenSwitch;
import com.eeepay.v2_library.view.TitleBar;

import java.util.Arrays;
import java.util.concurrent.TimeUnit;

import cn.eeepay.api.grpc.nano.AppInfo2ApiServiceGrpc;
import cn.eeepay.api.grpc.nano.AppInfo2Proto;
import cn.eeepay.api.grpc.nano.BannerApiServiceGrpc;
import cn.eeepay.api.grpc.nano.BannerProto;
import cn.eeepay.api.grpc.nano.NoticeApiServiceGrpc;
import cn.eeepay.api.grpc.nano.NoticeProto;
import cn.eeepay.api.grpc.nano.ReqBaseProto;
import io.grpc.ManagedChannel;


/**
 * Created by ljq on 2016/2/26 0026.
 * 销售中心页面
 */
public class FragmentSaleCenter extends Fragment implements View.OnClickListener {

    private final int BANNER = 1;
    private final int TOTAL_DATA = 2;
    private final int QR_CODE = 3;

    protected CustomDialog progressDialog;
    private CustomDisplayView displayView;//广告展示页
    private RelativeLayout advPager;//广告容器
    private View view;

    private PullToRefreshScrollView scrollView;
    //销售工具按钮:我要进件，进件查询，抓住商机，超级商户查询，超级交易查询，产品APP二维码；
    private Button intoPiecesBtn, piecesQueryBtn, grabOptyBtn, bisQueryBtn, tradeQueryBtn, qrCodeBtn;
    private TitleBar titleBar;
    //我的商户、 今日商户 、今日交易量、
    private LinearLayout rLayout_myBis, rLayout_todayMerchant, rLayout_todayTrade;
    private TextView myBis, newBis, todayTradeCount;

//    private QRCodeDialog qrCodeDialog;

    private SaleAdvAdapter adapter;

    private Context mContext;
//    private Intent intent;

    private GetSuperPushShareStatusAPI getSuperPushShareStatusAPI;//获取超级推分享开关状态

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_sale_center, container, false);
        mContext = getContext();
        getSuperPushShareStatus();
        initView();
        initLinstener();
//        initData();
        return view;
    }

    /**
     * 获取超级推分享开关状态
     */
    private void getSuperPushShareStatus() {
        getSuperPushShareStatusAPI = new GetSuperPushShareStatusAPI();
        getSuperPushShareStatusAPI.setResultCallBack(new GetSuperPushShareStatusAPI.ResultCallBack() {
            @Override
            public void onSucess(boolean msg) {
                if (msg) {
                    Drawable top = getResources().getDrawable(R.drawable.tuiguangma);
                    grabOptyBtn.setCompoundDrawablesWithIntrinsicBounds(null, top , null, null);
                    grabOptyBtn.setText("推广码");
                } else {
                    Drawable top = getResources().getDrawable(R.drawable.home_btn_opportunities);
                    grabOptyBtn.setCompoundDrawablesWithIntrinsicBounds(null, top , null, null);
                    grabOptyBtn.setText("抢占商机");
                }
            }
        });
        getSuperPushShareStatusAPI.getSuperPushShareStatusInfo();
    }


    /**
     * 初始化控件
     */
    private void initView() {
        titleBar = (TitleBar) view.findViewById(R.id.tb_sale_center);
        titleBar.setShowLeft(View.GONE);
        titleBar.setShowRight(View.VISIBLE);
//        titleBar.setRightResource(R.drawable.message);
        titleBar.setRightResource(R.drawable.icon_message);

        scrollView = (PullToRefreshScrollView) view.findViewById(R.id.pull_refresh_scroll_view);

        advPager = (RelativeLayout) view.findViewById(R.id.rl_adv);

        intoPiecesBtn = (Button) view.findViewById(R.id.btn_intoPieces);
        piecesQueryBtn = (Button) view.findViewById(R.id.btn_piecesQuery);
        grabOptyBtn = (Button) view.findViewById(R.id.btn_grabOpty);
        bisQueryBtn = (Button) view.findViewById(R.id.btn_superBisQuery);
        tradeQueryBtn = (Button) view.findViewById(R.id.btn_superTradeQuery);
        qrCodeBtn = (Button) view.findViewById(R.id.btn_appQrCode);
        rLayout_myBis = (LinearLayout) view.findViewById(R.id.rLayout_my_merchant);
        rLayout_todayTrade = (LinearLayout) view.findViewById(R.id.rLayout_todayTrade_count);
        rLayout_todayMerchant = (LinearLayout) view.findViewById(R.id.rLayout_today_merchant);
        myBis = (TextView) view.findViewById(R.id.tv_myBis_count);//我的商户
        newBis = (TextView) view.findViewById(R.id.tv_newBis_count);//新增商户
        todayTradeCount = (TextView) view.findViewById(R.id.tv_todayTrade_count);//今日交易量

        initData();

        sendHttpRequest(TOTAL_DATA);
    }

    /**
     * 初始化监听器
     */
    private void initLinstener() {
        titleBar.setRightOnClickListener(new TitleBar.RightBtnOnClickListener() {
            @Override
            public void onRightClick(View view) {
                ScreenSwitch.switchActivity(getContext(), NewsCenterActivity.class, null, 0);
                titleBar.setRightResource(R.drawable.icon_message);
                MyApplication.getInstance().hasNews = false;
            }
        });
        //下拉刷新
        scrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ScrollView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
                getSuperPushShareStatus();
                sendHttpRequest(TOTAL_DATA);
            }
        });

        intoPiecesBtn.setOnClickListener(this);
        piecesQueryBtn.setOnClickListener(this);
        grabOptyBtn.setOnClickListener(this);
        bisQueryBtn.setOnClickListener(this);
        tradeQueryBtn.setOnClickListener(this);
        qrCodeBtn.setOnClickListener(this);
        rLayout_myBis.setOnClickListener(this);
        rLayout_todayTrade.setOnClickListener(this);
        rLayout_todayMerchant.setOnClickListener(this);
    }

    /**
     * 网络请求
     *
     * @param taskId 请求ID
     */
    private void sendHttpRequest(int taskId) {
        showProgressDialog();
        GrpcUtils.getInstance().doGrpcTask(Constant.URL.URL, Constant.URL.PORT
                , taskId, new GrpcUtils.AsyncTaskListener() {
                    @Override
                    public Object doInBack(ManagedChannel channel, int taskId) {
                        switch (taskId) {
                            case TOTAL_DATA:
                                NoticeApiServiceGrpc.NoticeApiServiceBlockingStub stub = NoticeApiServiceGrpc
                                        .newBlockingStub(channel).withDeadlineAfter(30, TimeUnit.SECONDS);
//                                .withDeadlineAfter(Constant.grpc_time_out, TimeUnit.SECONDS);
                                NoticeProto.NoticeTotalRequest request = new NoticeProto.NoticeTotalRequest();
                                request.agentNo = UserInfo.getUserInfo2SP().getAgentNo();
                                request.oneAgentNo = UserInfo.getUserInfo2SP().getOneAgentNo();
                                request.agentNode = UserInfo.getUserInfo2SP().getAgentNode();
                                request.userId = UserInfo.getUserInfo2SP().getUserNo();
                                request.teamId = ConfigPorperties.getInstance().getTeamId();
                                request.agentLevel = UserInfo.getUserInfo2SP().getAgentLevel();
                                return stub.getNoticeTotal(request);
                            case BANNER:
                                BannerApiServiceGrpc.BannerApiServiceBlockingStub stub1 = BannerApiServiceGrpc
                                        .newBlockingStub(channel);
//                                .withDeadlineAfter(Constant.grpc_time_out, TimeUnit.SECONDS);
                                BannerProto.BannerRequest request1 = new BannerProto.BannerRequest();
                                request1.teamId = ConfigPorperties.getInstance().getTeamId();
                                request1.appNo = ConfigPorperties.getInstance().getAppNo();
                                request1.bannerPosition = "4";
                                return stub1.getBannerInfo(request1);
                            case QR_CODE://二维码
                                AppInfo2ApiServiceGrpc.AppInfo2ApiServiceBlockingStub stub2 = AppInfo2ApiServiceGrpc
                                        .newBlockingStub(channel);
                                ReqBaseProto.ReqTwoStr req = new ReqBaseProto.ReqTwoStr();
                                req.param1 = ConfigPorperties.getInstance().getAppNo();
                                req.param2 = ConfigPorperties.getInstance().getTeamId();
//                        AppInfo2Proto.AppInfo2 response = stub2.getAppInfo(req);
//                        return response;
                        }
                        return null;
                    }

                    @Override
                    public void updateUI(Object result, int taskId) {
                        dismissProgressDialog();
                        if (scrollView.isRefreshing()) {
                            scrollView.onRefreshComplete();
                        }
                        if (result == null) {
                            Toast.makeText(getContext(), "查询失败", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        switch (taskId) {
                            case TOTAL_DATA:
                                NoticeProto.NoticeTotalResponse response = (NoticeProto.NoticeTotalResponse) result;
                                if (!response.resMsg.status) {
                                    Toast.makeText(getContext(), response.resMsg.msg, Toast.LENGTH_SHORT).show();
                                    return;
                                }

//                        NumAnimUtil.startAnim(myBis,MathUtils.String2Int(response.merTotal),1000);
//                        NumAnimUtil.startAnim(newBis,MathUtils.String2Int(response.merDaytotal),1000);
//                        NumAnimUtil.startAnim(todayTradeCount,MathUtils.String2Float(response.agentDayAccount),1000);
                                //商户总数
                                myBis.setText(MathUtils.String2Int(response.merTotal) + "");
                                //今日商户总数
                                newBis.setText(MathUtils.String2Int(response.merDaytotal) + "");
                                //代理商今日交易金额
                                todayTradeCount.setText(MathUtils.String2Float(response.agentDayAccount) + "");

                                if (MyApplication.getInstance().hasNews) {
                                    titleBar.setRightResource(R.drawable.icon_new_message);
                                } else {
                                    if (!TextUtils.isEmpty(response.noticeTotal)
                                            && Integer.parseInt(response.noticeTotal) > 0) {//有新发布的消息
                                        titleBar.setRightResource(R.drawable.icon_new_message);
                                        MyApplication.getInstance().hasNews = true;
                                    } else {
                                        titleBar.setRightResource(R.drawable.icon_message);
                                    }
                                }

                                sendHttpRequest(BANNER);
                                break;
                            case BANNER:
                                BannerProto.BannerMsgResponse response1 = (BannerProto.BannerMsgResponse) result;
                                if (!response1.resMsg.status) {
                                    Toast.makeText(getContext(), response1.resMsg.msg, Toast.LENGTH_SHORT).show();
                                    return;
                                }
                                displayView.setDatas(Arrays.asList(response1.bannerMsg));

                                break;
                            case QR_CODE:
                                AppInfo2Proto.AppInfo2 response2 = (AppInfo2Proto.AppInfo2) result;
                                LogUtils.d(response2.toString());
//                        if(!response2.resStatus.status){
//                            Toast.makeText(mContext, response2.resStatus.msg, Toast.LENGTH_SHORT).show();
//                            return;
//                        }
//                        AppInfo.getInstance().setCodeUrl(response2.codeUrl);
//                        AppInfo.getInstance().setAppName(response2.appName);
//                        AppInfo.getInstance().setApply(response2.apply);
//                        AppInfo.getInstance().setStatus(response2.status);
//                        AppInfo.getInstance().setVersion(response2.version);
//                        if(qrCodeDialog == null){
//                            qrCodeDialog = new QRCodeDialog(mContext);
//                            qrCodeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
//                        }
//                        qrCodeDialog.show();
                                break;
                        }

                    }
                });
    }

    @Override

    public void onResume() {
        if (MyApplication.getInstance().hasNews) {
            titleBar.setRightResource(R.drawable.icon_new_message);
        } else {
            titleBar.setRightResource(R.drawable.icon_message);
        }
        super.onResume();
    }

    /**
     * 初始化数据
     */
    private void initData() {

        adapter = new SaleAdvAdapter(getContext());

        displayView = new CustomDisplayView(getContext());
        displayView.setAdapter(adapter);

        advPager.addView(displayView);

//        List<BannerProto.BannerMsg> datas = new ArrayList<>();
//        BannerProto.BannerMsg bannerMsg = new BannerProto.BannerMsg();
//        bannerMsg.bannerAttachment = "https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm" +
//                "9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1475203655&di=" +
//                "dc7b75180e32f7548b0e0b38fa0593e2&src=http://news.cnhubei.com/xw/yl/201" +
//                "308/W020130806649903994735.jpg";
//        datas.add(bannerMsg);
//        BannerProto.BannerMsg bannerMsg2 = new BannerProto.BannerMsg();
//        bannerMsg2.bannerAttachment = "http://s1.dwstatic.com/group1/M00/4A/42/23824d945cdc" +
//                "12fab8ba6e5941cfd1d8.jpg";
//        datas.add(bannerMsg2);
//
//        displayView.setDatas(datas);


    }


    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.rLayout_my_merchant://我的商户
                switchActivity(MyMerchantActivity.class, Constant.MY_MERCHANT);
//                switchActivity(MainPicActivity.class, Constant.MY_MERCHANT);
                break;
            case R.id.rLayout_today_merchant://今日商户
                switchActivity(MyMerchantActivity.class, Constant.TODAY_MERCHANT);
                break;
            case R.id.rLayout_todayTrade_count://七日交易
                switchActivity(WeekTradeActivity.class, Constant.WEEK_TRADE);
                break;
            case R.id.btn_intoPieces://我要进件
                ScreenSwitch.switchActivity(getContext(), IntoPiecesActivity.class, null, 0);
                break;
            case R.id.btn_piecesQuery://进件查询
                ScreenSwitch.switchActivity(getContext(), IntoQueryActivity.class, null, 0);
                break;
            case R.id.btn_grabOpty://抓住商机
                if (grabOptyBtn.getText().toString().equals("推广码")) {
//                Toast.makeText(getActivity(),"敬请期待",Toast.LENGTH_SHORT).show();
//                ScreenSwitch.switchActivity(getContext(), GrabBisActivity.class, null, 0);
                    ScreenSwitch.switchActivity(getContext(), ShareActionActivity.class, null, 0);
                } else {
                    Toast.makeText(getActivity(), "敬请期待", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_superBisQuery://商户超级查询
//                Toast.makeText(getActivity(),"敬请期待",Toast.LENGTH_SHORT).show();
                ScreenSwitch.switchActivity(getContext(), MerchantQueryActivity.class, null, 0);
                break;
            case R.id.btn_superTradeQuery://交易超级查询
                ScreenSwitch.switchActivity(getContext(), TradeQueryActivity.class, null, 0);
                break;
            case R.id.btn_appQrCode://产品APP二维码
//                sendHttpRequest(QR_CODE);
//                Toast.makeText(getActivity(),"敬请期待",Toast.LENGTH_SHORT).show();
                ScreenSwitch.switchActivity(getContext(), QRCodeActivity2.class, null, 0);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void switchActivity(Class<?> decsClass, String intentFlag) {
        Bundle bundle = new Bundle();
        bundle.putString(Constant.INTENT_FLAG, intentFlag);
        ScreenSwitch.switchActivity(getContext(), decsClass, bundle, 0);
    }

    public void showProgressDialog() {
        if (progressDialog == null) {
            progressDialog = DialogUtil.getHorizontalProgressDialog(mContext);
        }
        progressDialog.show();
    }

    public void showProgressDialog(String string) {
        if (progressDialog == null) {
            progressDialog = DialogUtil.getHorizontalProgressDialog(mContext, string);
        }
        progressDialog.show();
    }

    public void dismissProgressDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }
}